package edu.xidian.onlinedocument.utils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 只有静态方法的静态类
 * 用于将一串字符串转换为sha256加密的32字节byte数组，再将byte数组转换为长度为64的16进制字符串输出
 */
public class SHA256Util {
    /**
     * 将一串字符串用SHA256加密，得到一串长度为64的16进制字符串
     * @param string
     * @return
     */
    public static String getSHA256(String string){
        MessageDigest messageDigest;
        String encodeString = "";
        try{
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(string.getBytes(StandardCharsets.UTF_8));
            encodeString = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return encodeString;
    }

    /**
     * 将byte（8位）转为16进制（4位）
     * @param src 源byte数组
     * @return 目标字符串
     */
    private static String byte2Hex(byte[] src){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for(int i = 0; i < src.length; i++){
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if(hv.length() == 1){
                stringBuffer.append(0);
            }
            stringBuffer.append(hv);
        }
        return stringBuffer.toString();
    }
}
